<template>
  <div class="login">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      label-position="top"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="form.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 引入封装的接口功能组件
import { login, getUserInfo } from "@/services/user";

export default {
  name: "LoginIndex",
  data() {
    return {
      // 存储表单数据的对象
      form: {
        userName: "admin",
        password: "123456",
      },
      // 用于设置表单校验规则
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 18,
            message: "密码长度为 6 到 18 位",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 登录功能
    async onSubmit() {
      try {
        await this.$refs.form.validate();
        login(this.form)
          .then((res) => {
            const { data } = res;
            if (data.data) {
              this.$store.commit("setUserToken", data.data);
              getUserInfo().then((res) => {
                if (res.data.data) {
                  this.$store.commit("setUser", res.data.data);
                  this.$message.success("登录成功");
                  if (this.form.userName == "admin") {

                    this.$store.commit("setUserRole", 'admin');
                  } else {
                    this.$store.commit("setUserRole", 'teacher');
                  }
                  this.$router.push(this.$route.query.redirect || "/");
                }
              });
            } else {
              this.$message.error("登录失败");
            }
          })
          .catch((e) => {
            console.log(e);
          });
      } catch (err) {
        // 设置校验失败后的功能（提示）
        console.log("没有通过校验");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.login {
  height: 100vh;
  display: flex;
  // 设置内部元素垂直水平居中
  justify-content: center;
  align-items: center;

  .el-form {
    background-color: #fff;
    padding: 20px;
    width: 300px;
    border-radius: 10px;

    .el-button {
      width: 100%;
    }
  }
}
</style>
